'use strict';

const BaseService = require('../base');
const { Op } = require("sequelize");

const {
  CommonDeletedEnum, CommonUserTypeEnum
} = require("../../utils/enum");
const {
  listToTree
} = require("../../utils");
class BannerService extends BaseService {
  static get modelName() {
    return 'System.SystemUser';
  }

  async login(data) {
    const { ctx } = this;
    const { username, password, type } = data;
    if (!username) {
      throw new Error('缺少用户名');
    }
    if (!password) {
      throw new Error('缺少密码');
    }
    if (type === CommonUserTypeEnum.SYSTEM_USER) {
      const result = await this.model.findOne({
        where: { username, deleted: CommonDeletedEnum.NOT_DELETED }
      });
      if (!result) {
        throw new Error('账号不存在');
      }
      if (result.password !== password) {
        throw new Error('密码错误');
      }
      // 更新最后一次登录时间
      await this.model.update({
        lastLoginTime: new Date(),
      }, {
        where: {
          id: result.id
        }
      });
      return result.dataValues;
    } else {
      const result = await this.ctx.model.Business.TicketShop.findOne({
        where: { username, deleted: CommonDeletedEnum.NOT_DELETED }
      });
      if (!result) {
        throw new Error('账号不存在');
      }
      if (result.password !== password) {
        throw new Error('密码错误');
      }
      return result.dataValues;
    }
  }

  async getMenu() {
    // 先查询他的角色
    const roleUserList = await this.ctx.model.System.SystemUserRole.findAll({
      where: {
        user_id: this.ctx.user.id,
        deleted: CommonDeletedEnum.NOT_DELETED
      },
      attributes: ['role_id'],
      raw: true
    })
    // 查询角色
    const roleList = await this.ctx.model.System.SystemRole.findAll({
      where: {
        id: roleUserList.map(item => item.role_id),
        deleted: CommonDeletedEnum.NOT_DELETED
      },
      raw: true
    })
    // 判断是否超级管理员
    let hasSuperAdmin = roleList.some(item => item.code === 'super_admin')
    if (hasSuperAdmin) {
        // 查询所有菜单
        return this.ctx.service.system.systemMenu.getSuperAdminMenuTree()
    } else {
      // 合并角色
      const roleIds = roleList.map(item => item.id)
      const roleMenuList = await this.ctx.model.System.SystemRoleMenu.findAll({
        where: {
          role_id: roleIds,
          deleted: CommonDeletedEnum.NOT_DELETED
        },
        raw: true
      })
      // 去重
      const menuIds = roleMenuList.map(item => item.menuId)
      const menuList = await this.ctx.model.System.SystemMenu.findAll({
        where: {
          id: menuIds,
          deleted: CommonDeletedEnum.NOT_DELETED
        },
        raw: true
      })
      return listToTree(menuList).sort((a, b) => a.sort - b.sort)
    }
    return []
  }

  setAfterPageQuery() {
    return {
      // 账号不等于admin
      username: {
        [Op.ne]: 'admin'
      }
    }
  }
}

module.exports = BannerService;
